"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : autocommit
Case Name   : 关闭自动提交，自定义函数并调用，回滚/提交，新开会话查询
Create At   : 2023/01/17
@zou_jialiang0501162244
Description :
    1、兼容B库建表并插入数据
    2、会话1：关闭自动提交，创建函数，会话2查询后会话1执行commit、调用函数，
       会话2查询后rollback函数调用，查询表数据，再次调用函数，提交
    3、会话2：查询函数和表数据
    4、清理环境
Expect      :
    1、成功
    2、执行成功，查询3条数据，回滚后2条数据
    3、函数在会话1提交后存在，表中2条数据，会话1提交后3条数据
    4、成功
History     :
"""

import os
import time
import unittest

from testcase.utils.Logger import Logger
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.ComThread import ComThread


class TestAutocommit(unittest.TestCase):

    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.constant = Constant()
        self.tb_name = 't_autocommit_0037'
        self.function = 'f_autocommit_0037'
        self.db_name = 'db_autocommit_0037'
        self.log.info("-----预置兼容B库-----")
        preset_db = f"drop database if exists {self.db_name};" \
                    f"create database {self.db_name} dbcompatibility 'B';"
        preset_db_res = self.pri_sh.execut_db_sql(preset_db)
        self.log.info(preset_db_res)
        self.assertIn(self.constant.CREATE_DATABASE_SUCCESS, preset_db_res,
                      f"创建兼容B库失败")

    def test_autocommit(self):
        text1 = '-----step1:兼容B库建表并插入数据;expect:成功-----'
        self.log.info(text1)
        preset_tb = f"drop table if exists {self.tb_name};" \
                    f"create table {self.tb_name}(" \
                    f"itemno integer,quantity integer,price numeric);" \
                    f"insert into {self.tb_name} values" \
                    f"(100, 15, 11.2), (101, 22, 12.3);"
        preset_res = self.pri_sh.execut_db_sql(preset_tb, dbname=self.db_name)
        self.log.info(preset_res)
        self.assertIn(self.constant.CREATE_TABLE_SUCCESS, preset_res,
                      f"建表失败: {text1}")
        self.assertIn(self.constant.INSERT_SUCCESS_MSG, preset_res,
                      f"insert失败: {text1}")

        text2 = '-----step2:会话1关闭自动提交，创建函数，会话2查询后commit，' \
                '调用函数，会话2查询后rollback，查询表数据，再次调用函数，' \
                '提交;expect:执行成功，查询3条数据，回滚后2条数据-----'
        self.log.info(text2)
        sql1 = f'''set autocommit = 0;
        drop function if exists {self.function}();
        create function {self.function}(p_itemno in integer)
        returns table(quantity integer, total numeric) as \$\$
        begin
        insert into {self.tb_name} values(1020, 50, 9874.5);
        update {self.tb_name} set quantity=p_itemno where itemno = 1020;
        return query select {self.tb_name}.quantity, 
        {self.tb_name}.quantity * {self.tb_name}.price 
        from {self.tb_name} where itemno = p_itemno;
        end;
        \$\$ language plpgsql; 
        select pg_sleep(3);
        commit;
        select {self.function}(101);
        select * from {self.tb_name};
        select pg_sleep(3);
        rollback;
        select count(*) from {self.tb_name};
        select {self.function}(101);
        commit;
        '''
        session1 = ComThread(self.pri_sh.execut_db_sql,
                             args=(sql1, '', self.db_name))
        session1.setDaemon(True)
        session1.start()
        time.sleep(1.5)

        text3 = '-----step3:会话2查询函数和表数据;expect:函数在会话1提交后' \
                '存在，表中两条数据，3-----'
        self.log.info(text3)
        sql2 = f"select * from pg_proc where proname = '{self.function}';" \
               f"select pg_sleep(3);" \
               f"select proname from pg_proc " \
               f"where proname = '{self.function}';" \
               f"select * from {self.tb_name};" \
               f"select pg_sleep(3);" \
               f"select count(*) from {self.tb_name};"
        session2 = ComThread(self.pri_sh.execut_db_sql,
                             args=(sql2, '', self.db_name))
        session2.setDaemon(True)
        session2.start()
        session1.join(10)
        session2.join(10)
        res1 = session1.get_result()
        self.log.info(f'session1_results:\n {res1}')
        res2 = session2.get_result()
        self.log.info(f'session2_results:\n {res2}')
        self.assertIn('SET', res1, f"关闭自动提交失败: {text2}")
        self.assertIn(self.constant.CREATE_FUNCTION_SUCCESS_MSG, res1,
                      f"创建函数失败: {text2}")
        self.assertEqual(res1.count('(22,264)'), 2, f"调用函数失败: {text2}")
        self.assertIn('1020 |      101 |  9875', res1, f"执行失败: {text2}")
        self.assertEqual(res1.count(self.constant.COMMIT_SUCCESS_MSG), 2,
                         f"执行失败: {text2}")
        self.assertIn(self.constant.ROLLBACK_MSG, res1, f"执行失败: {text2}")
        self.assertIn('2', res1.splitlines()[-9], f"执行失败: {text2}")
        self.assertEqual('(0 rows)', res2.splitlines()[2], f"执行失败: {text3}")
        self.assertIn(self.function, res2, f"执行失败: {text3}")
        self.assertIn('100 |       15 |    11', res2, f"执行失败: {text3}")
        self.assertIn('101 |       22 |    12', res2, f"执行失败: {text3}")
        self.assertEqual(res2.splitlines()[-2].strip(), '3', f"执行失败: {text3}")

    def tearDown(self):
        text4 = '-----step4:清理环境 expect:成功-----'
        self.log.info(text4)
        drop_db_res = self.pri_sh.execut_db_sql(
            f"drop database if exists {self.db_name};")
        self.log.info(drop_db_res)
        self.assertIn(self.constant.DROP_DATABASE_SUCCESS, drop_db_res,
                      f"执行失败: {text4}")
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
